<template>
  <div class="maincontent">
    <el-form
      :inline="true"
      ref="ruleForm"
      :model="formData"
      label-width="90px"
      :rules="formDataRules"
    >
      <div class="maintitle">基本信息</div>
      <div class="formcontent">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="formData.name" style="width:200px;"></el-input>
        </el-form-item>
        <!-- <el-form-item label="项目编号">
                    <el-input v-model="form.number" style="width:200px;"></el-input>
        </el-form-item>-->
      </div>
      <div>
        <el-form-item label="所属区县" prop="district">
          <el-select v-model="formData.district" placeholder="所属区县" @change="handleSelectDistrict">
            <el-option
              v-for="item in districtMessages"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="乡镇" prop="countryside">
          <el-select
            v-model="formData.countryside"
            placeholder="所属乡镇"
            @change="handleSelectCountry"
          >
            <el-option
              v-for="item in countryMessages"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="行政村" prop="village">
          <el-select v-model="formData.village" placeholder="所属村落">
            <el-option
              v-for="item in villageMessages"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="maintitle" style="margin-top:40px;">详细信息</div>
      <div class="formcontent">
        <el-form-item label="项目级别" prop="level">
          <el-select v-model="formData.level" placeholder="请选择级别">
            <el-option label="市级" :value="0"></el-option>
            <el-option label="区县级" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目年度" v-show="formData.level == 0" prop="year">
          <el-date-picker v-model="formData.year" type="year" placeholder="选择年" value-format="yyyy"></el-date-picker>
        </el-form-item>
        <el-form-item label="项目类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择类型">
            <el-option
              v-for="item in projectTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="图编号" v-show="formData.level == 0" prop="frameNumber">
          <el-input v-model="formData.frameNumber" style="width:200px;"></el-input>
        </el-form-item>-->
        <el-form-item label="项目工期" prop="duration">
          <el-input v-model="formData.duration" :min="1" style="width:200px;" type="number">
            <template slot="append">月</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="投资回收期"
          :min="1"
          label-width="95px"
          v-show="formData.level == 0"
          prop="recover"
        >
          <el-input v-model="formData.recover" style="width:200px;" type="number" min="0">
            <template slot="append">月</template>
          </el-input>
        </el-form-item>
        <el-form-item label="是否属于高标准基本农田项目" label-width="210px" prop="isStandard">
          <el-select v-model="formData.isStandard">
            <el-option label="是" :value="0"></el-option>
            <el-option label="否" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="maintitle" style="margin-top:40px;">片块选择</div>
      <div class="formcontent">
        <div class="module-item">
          <div class="module-item-content" style="padding-bottom:35px;overflow: hidden;">
            <div class="form">
              <el-form :inline="true" label-position="right" label-width="90px">
                <el-form-item label="所在乡镇">
                  <el-tooltip
                    effect="dark"
                    :disabled="
                      displayZyxzStr == null || displayZyxzStr == ''
                        ? true
                        : false
                    "
                    :content="displayZyxzStr"
                  >
                    <el-select
                      @change="handleTownChange"
                      v-model="selectedTown"
                      filterable
                      placeholder="--请选择--"
                      clearable
                      :loading="townLoading"
                    >
                      <el-option
                        v-for="(item, index) in townData"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="行政村名称">
                  <el-tooltip
                    effect="dark"
                    :disabled="
                      displayXzcStr == null || displayXzcStr == ''
                        ? true
                        : false
                    "
                    :content="displayXzcStr"
                  >
                    <el-select v-model="selectedVillage" placeholder="--请选择--" filterable clearable>
                      <el-option
                        v-for="(item, index) in villageData"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-tooltip>
                </el-form-item>
                <el-form-item>
                  <el-button @click="handleListQuery" type="primary">查询</el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-table :data="pkSelectedData" highlight-current-row>
              <el-table-column prop="applicantName" label="权利人"></el-table-column>
              <el-table-column label="乡镇名称">
                <template slot-scope="scope">
                  {{
                  scope.row.town.name
                  }}
                </template>
              </el-table-column>
              <el-table-column label="行政村名称">
                <template slot-scope="scope">
                  {{
                  scope.row.village.name
                  }}
                </template>
              </el-table-column>
              <el-table-column prop="address" label="通讯地址"></el-table-column>
              <el-table-column prop="landArea" label="使用权面积（㎡）"></el-table-column>
              <!-- <el-table-column label="片块编号" width="200px">
                <template slot-scope="scope">
                  <span>片块</span>
                  <el-input
                    class="pkInput"
                    type="number"
                    style="width: 50px;"
                    v-model="scope.row.villageIndex"
                    placeholder="片块"
                  />
                  <span>-</span>
                  <el-input
                    class="pkInput"
                    type="number"
                    style="width: 50px;"
                    v-model="scope.row.landIndex"
                    placeholder="片块"
                  />
                </template>
              </el-table-column>-->
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="handleRemovePk(scope.$index)" type="text">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-dialog :close-on-click-modal="false" title="选择片块" :visible.sync="pkDialog">
      <div style="overflow: hidden;">
        <el-table
          @selection-change="handleSelectionChange"
          v-loading="listLoading"
          :data="list"
          element-loading-text="加载中"
          highlight-current-row
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="obligeeName" label="权利人"></el-table-column>
          <el-table-column label="乡镇名称">
            <template slot-scope="scope">{{ scope.row.town.name }}</template>
          </el-table-column>
          <el-table-column label="行政村名称">
            <template slot-scope="scope">{{ scope.row.village.name }}</template>
          </el-table-column>
          <el-table-column prop="address" label="通讯地址"></el-table-column>
          <el-table-column prop="landArea" label="使用权面积（㎡）"></el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            :current-page="listQuery.page"
            @size-change="handleSizeChange"
            @current-change="changePage"
            :page-size="listQuery.size"
            layout="prev, pager, next, jumper, sizes"
            :total="total"
          ></el-pagination>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="pkDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleAddPk">添 加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDistrictInformation,
  getCountrysideInformation,
  getNewProjectAdd,
  getProjectType
} from '@/api/projectManage/districtProject.js'
import {
  getDicData,
  getTownData,
  getVillageData,
  getListLandByRegionId,
  add,
  calculateArea
} from '@/api/project/xmkgh/xmprezz'
export default {
  data() {
    return {
      formData: {
        name: '',
        district: '',
        countryside: '',
        village: '',
        year: '',
        level: 1,
        type: '',
        // frameNumber: "",
        duration: 1,
        recover: 1,
        isStandard: 1,
        landId: []
      },
      formDataRules: {
        name: [
          {
            required: true,
            message: '请输入项目名称',
            trigger: 'chan'
          }
        ],
        district: [
          {
            required: true,
            message: '请选择所属区县',
            trigger: 'change'
          }
        ],
        countryside: [
          {
            required: true,
            message: '请选择所属乡镇',
            trigger: 'blur'
          }
        ],
        village: [
          {
            required: true,
            message: '请选择所属村落',
            trigger: 'blur'
          }
        ],
        level: [
          {
            required: true,
            message: '请选择级别',
            trigger: 'change'
          }
        ],
        year: [
          {
            required: true,
            message: '请选择年限',
            trigger: 'blur'
          }
        ],
        type: [
          {
            required: true,
            message: '请选择类型',
            trigger: 'change'
          }
        ],
        duration: [
          {
            required: true,
            message: '请输入项目工期',
            trigger: 'blur'
          }
        ],
        recover: [
          {
            required: true,
            message: '请选择投资回收期',
            trigger: 'blur'
          }
        ],
        isStandard: [
          {
            required: true,
            message: '请选择是否属于高标准基本农田项目',
            trigger: 'change'
          }
        ]
      },
      districtMessages: [], //区县信息
      countryMessages: [], //乡镇信息
      villageMessages: [], //行政村信息
      projectTypeList: [], //项目类型

      /* 片块选择 */
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        size: 10,
        regionId: null,
        selectedLand: null
      },
      validateForm: {
        name: null,
        level: [],
        projectTypeId: null,
        projectIndexId: null,
        isChange: [],
        landUtilizePlanName: null,
        landRepairPlanName: null,
        townConstructPlanName: null,
        projectLandVos: [],
        districtId: null,
        townId: null,
        landArea: null,
        cityId: null
      },
      rules: {
        name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        level: [{ required: true, message: '请选择项目级别', trigger: 'blur' }],
        projectTypeId: [
          { required: true, message: '请选择项目类型', trigger: 'blur' }
        ],
        projectIndexId: [
          { required: true, message: '请选择指标使用方向', trigger: 'blur' }
        ],
        isChange: [
          {
            required: true,
            message: '请选择是否涉及土地利用现状变更',
            trigger: 'blur'
          }
        ],
        landUtilizePlanName: [
          { required: true, message: '请输入土地利用规划名称', trigger: 'blur' }
        ],
        landRepairPlanName: [
          { required: true, message: '请输入土地整治规划名称', trigger: 'blur' }
        ],
        townConstructPlanName: [
          { required: true, message: '请输入乡镇建设规划名称', trigger: 'blur' }
        ]
      },
      PROJECT_INDEX: [],
      PROJECT_TYPE: [],

      displaySsqx: null,
      displayXzc: null,
      displayZyxz: null,
      displaySsqxStr: null,
      displayXzcStr: null,
      displayZyxzStr: null,
      displayTdsyqmj: null,

      townData: [],
      selectedTown: null,
      villageData: [],
      selectedVillage: null,

      pkDialog: false,
      pkAddData: [],
      pkSelectedData: [],
      townLoading: false,
      landIdArrData: [] //选择的片块列表
    }
  },
  watch: {
    pkSelectedData(newVal, oldVal) {
      let landIdArr = []
      this.displayTdsyqmj = null
      newVal.forEach(item => {
        landIdArr.push(item.id)
        // this.displayTdsyqmj += item.landArea;
      })
      this.countArea(landIdArr)
      // 计算面积
      this.listQuery.selectedLand = landIdArr.join(',')
      this.formData.landId = landIdArr
    }
  },
  methods: {
    handleRemovePk(index) {
      this.pkSelectedData.splice(index, 1)

      // this.pkSelectedData = this.pkSelectedData.concat(
      //   this.handlePkSelectedData(this.pkAddData)
      // );

      // this.handleResetName(this.pkSelectedData);
    },
    countArea(arr) {
      var data = {
        landIdList: arr.join(',')
      }
      calculateArea(data).then(res => {
        this.displayTdsyqmj = res.data
        this.validateForm.landArea = res.data
      })
    },
    // 获取当前年份
    getCurrentYear: function() {
      var myDate = new Date()
      this.formData.year = String(myDate.getFullYear())
    },
    getInitData: function() {
      this.getDistrictMessage()
      this.getProjectType()
    },
    //区县信息勾选回调
    handleSelectDistrict: function(id) {
      this.formData.countryside = ''
      this.countryMessages = []
      this.formData.village = ''
      this.villageMessages = []
      this.getCountryMessage(id)
    },
    //乡镇信息勾选回调
    handleSelectCountry: function(id) {
      this.formData.village = ''
      this.villageMessages = []
      this.getVillageMessage(id)
    },
    //获取区县信息
    getDistrictMessage: function() {
      getDistrictInformation().then(res => {
        this.districtMessages = res.data
        // this.formData.district = res.data[0].id;
        // this.getCountryMessage(res.data[0].id);
      })
    },
    //获取乡镇信息
    getCountryMessage: function(id) {
      getCountrysideInformation({ parentId: id }).then(res => {
        this.countryMessages = res.data
      })
    },
    //获取行政村信息
    getVillageMessage: function(id) {
      getCountrysideInformation({ parentId: id }).then(res => {
        this.villageMessages = res.data
      })
    },
    //获取项目类型
    getProjectType: function() {
      getProjectType().then(res => {
        this.projectTypeList = res.data
      })
    },
    //提交保存
    handleSubmit: function() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.formData.duration = this.formData.duration * 1
          this.formData.recover = this.formData.recover * 1
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          getNewProjectAdd(this.formData)
            .then(res => {
              loading.close()
              this.$message({
                message: '新建项目成功！',
                type: 'success'
              })
              setTimeout(() => {
                this.$router.push('/projectManagement/planningStage/dealwith')
              }, 2000)
            })
            .catch(res => {
              loading.close()
            })
        } else {
          return false
        }
      })
    },

    /* 片块选择 */
    handleTownChange() {
      this.selectedVillage = ''
      this.getVillageData()
    },
    handleListQuery() {
      if (this.selectedTown == null || this.selectedTown == '') {
        this.$alert('请选择所在乡镇', '提示')
        return
      }
      if (this.selectedVillage == null || this.selectedVillage == '') {
        this.listQuery.regionId = this.selectedTown
      } else {
        this.listQuery.regionId = this.selectedVillage
      }
      this.pkDialog = true
      this.changePage(1)
    },
    handleSelectionChange(arr) {
      this.pkAddData = arr
    },
    handleSizeChange(size) {
      this.listQuery.size = size
      this.getListLandByRegionId()
    },
    changePage(page) {
      this.listQuery.page = page
      this.getListLandByRegionId()
    },
    handleAddPk() {
      if (this.pkAddData.length == 0) {
        this.$alert('请至少选择一个片块', '提示')
        return
      }
      // this.pkSelectedData = this.handlePkSelectedData(this.pkSelectedData.concat(this.pkAddData));
      this.pkSelectedData = this.pkSelectedData.concat(this.pkAddData)

      // this.handleResetName(this.pkSelectedData);
      this.pkDialog = false
    },
    getTownData() {
      this.townLoading = true
      getTownData()
        .then(res => {
          this.townLoading = false
          this.townData = res.data
        })
        .catch(err => {
          this.townLoading = false
        })
    },
    getVillageData() {
      if (this.selectedTown == null || this.selectedTown == '') {
        this.selectedVillage = null
        this.villageData = []
        return
      }
      getVillageData({
        parentId: this.selectedTown
      }).then(res => {
        this.villageData = res.data
      })
    },
    getListLandByRegionId() {
      this.listLoading = true
      getListLandByRegionId(this.listQuery)
        .then(res => {
          this.listLoading = false
          res.data.rows.forEach(item => {
            item['villageIndex'] = null
            item['landIndex'] = null
          })
          this.list = res.data.rows
          this.total = res.data.total
        })
        .catch(err => {
          this.listLoading = false
        })
    }
  },
  created() {
    this.getInitData()
    this.getCurrentYear()
    /* 片块选择 */
    this.getTownData()
  }
}
</script>

<style lang="scss" scoped>
.maincontent {
  padding: 30px 40px;
  .maintitle {
    font-size: 18px;
    font-family: PingFang SC;
    font-weight: bold;
    line-height: 25px;
    color: #4d4d4d;
  }
  .formcontent {
    margin-top: 30px;
    width: 1000px;
  }
}

.pagination-container {
  float: right;
  margin: 30px;
}
</style>
